package com.muchenx.controller;

import com.gynsh.base.entity.BaseEntity;
import com.gynsh.base.entity.BaseLogicEntity;
import com.gynsh.base.entity.BasePureEntity;
import com.muchenx.db.CodeCache;
import com.muchenx.db.DatasourceHelper;
import com.muchenx.db.DBCache;
import com.muchenx.util.UIComponentUtil;
import com.muchenx.util.Util;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Paint;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

public class TopViewController {

    private final static StringBuffer INFO = new StringBuffer()
            .append("       JDK Version\t").append(System.getProperty("java.version")).append("\n")
            .append("        JDK Vendor\t").append(System.getProperty("java.vendor")).append("\n")
            .append("         Java Home\t").append(System.getProperty("java.home")).append("\n")
            .append("Java Class Version\t").append(System.getProperty("java.class.version")).append("\n")
            .append("    JavaFX Version\t").append(FXMLLoader.JAVAFX_VERSION).append("\n")
            .append("           OS Name\t").append(System.getProperty("os.name")).append("\n")
            .append("        OS Version\t").append(System.getProperty("os.version")).append("\n")
            .append("           OS Arch\t").append(System.getProperty("os.arch")).append("\n")
            .append("        Support DB Type\tMySQL");

    private static final Pattern IPV4_REGEX = Pattern.compile("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");

    @FXML
    public void onAbout(ActionEvent actionEvent) {
        UIComponentUtil.infoAlert(INFO.toString());
    }

    @FXML
    public void onSettingDatasource(ActionEvent actionEvent) {
        VBox vBox = new VBox();
        vBox.setFillWidth(true);
        vBox.setPrefWidth(300);
        vBox.setPrefHeight(300);
        final TextField ipTextField = UIComponentUtil.textField("请输入数据库访问IP(x.x.x.x)", DBCache.ip);
        final TextField portTextField = UIComponentUtil.textField("请输入数据库访问端口(1~65535)", String.valueOf(DBCache.port));
        final TextField dbTextField = UIComponentUtil.textField("请输入数据库名", DBCache.db);
        final TextField userTextField = UIComponentUtil.textField("请输入数据库用户名", DBCache.user);
        final TextField pwdTextField = UIComponentUtil.textField("请输入数据库访问密码", DBCache.pwd);
        vBox.getChildren().addAll(
                UIComponentUtil.wrapTextField(ipTextField, "IP地址"),
                UIComponentUtil.wrapTextField(portTextField, "端口"),
                UIComponentUtil.wrapTextField(dbTextField, "数据库名"),
                UIComponentUtil.wrapTextField(userTextField, "数据库用户"),
                UIComponentUtil.wrapTextField(pwdTextField, "访问密码"));
        Alert alert = UIComponentUtil.createCustomConfirm("数据源配置", 300, 300, vBox);
        // 修改按钮描述
        alert.getDialogPane().getButtonTypes().setAll(
                new ButtonType("保存", ButtonBar.ButtonData.OK_DONE),
                new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE));

        portTextField.textProperty().addListener((obs, oldValue, newValue) -> checkPort(newValue));

        alert.showAndWait().ifPresent(buttonType -> {
            if (ButtonType.OK.getButtonData().equals(buttonType.getButtonData())) {
                if (!checkIp(ipTextField.getText())
                        || !checkPort(portTextField.getText())
                        || !checkDb(dbTextField.getText())
                        || !checkDUser(userTextField.getText())
                        || !checkPwd(pwdTextField.getText())) {
                    return;
                }
                initDatasource(ipTextField.getText().trim(),
                        Integer.parseInt(portTextField.getText().trim()),
                        dbTextField.getText().trim(),
                        userTextField.getText().trim(),
                        pwdTextField.getText().trim());
                UIComponentUtil.infoAlert("数据源更新并初始化成功！");
                return;
            }
            UIComponentUtil.errorAlert("已取消操作！");
        });

    }

    private void initDatasource(String ip, int port, String db, String user, String pwd) {
        DatasourceHelper.init(ip, port, db, user, pwd);
        DBCache.ip = ip;
        DBCache.port = port;
        DBCache.db = db;
        DBCache.user = user;
        DBCache.pwd = pwd;
    }

    private boolean checkIp(String ip) {
        if (!("localhost".equalsIgnoreCase(ip) || IPV4_REGEX.matcher(ip.trim()).matches())) {
            UIComponentUtil.errorAlert("IP地址不合法，格式：x.x.x.x（x为0~255之间）");
            return false;
        }
        return true;
    }

    private boolean checkPort(String portStr) {
        if (!Util.isDigit(portStr.trim())) {
            UIComponentUtil.errorAlert("端口不合法，只能在1~65535之间");
            return false;
        }
        int port = Integer.parseInt(portStr.trim());
        if (port < 1 || port > 65535) {
            UIComponentUtil.errorAlert("端口不合法，只能在1~65535之间");
            return false;
        }
        return true;
    }

    private boolean checkDb(String db) {
        if (StringUtils.isEmpty(db)) {
            UIComponentUtil.errorAlert("数据库名不能为空");
            return false;
        }
        return true;
    }

    private boolean checkDUser(String user) {
        if (StringUtils.isEmpty(user)) {
            UIComponentUtil.errorAlert("数据库用户名不能为空");
            return false;
        }
        return true;
    }

    private boolean checkPwd(String pwd) {
        if (StringUtils.isEmpty(pwd)) {
            UIComponentUtil.errorAlert("数据库访问密码不能为空");
            return false;
        }
        return true;
    }

    @FXML
    public void onSettingCode(ActionEvent actionEvent) {
        VBox vBox = new VBox();
        vBox.setFillWidth(true);
        vBox.setPrefWidth(300);
        vBox.setPrefHeight(300);
        final TextField parentPkgTextField = UIComponentUtil.textField("生成代码的父级包名", CodeCache.parentPackage);

        // 创建一个下拉选项,创建一个 ToggleGroup，用于将 RadioButton 组合在一起
        // 创建一个垂直布局容器（VBox），用于放置单选按钮
        HBox superClsBox = new HBox();
        superClsBox.setPadding(new Insets(20, 0, 0, 0));
        superClsBox.setSpacing(10);
        superClsBox.setAlignment(Pos.CENTER_LEFT);

        ComboBox<Label> box = new ComboBox<>();
        box.setStyle("-fx-background-color: transparent;-fx-text-fill: #000; -fx-prompt-text-fill: #000; -fx-progress-color: #000; -fx-border-color: lightgray;");
        box.setPrefWidth(180);
        box.getItems().addAll(
                new Label(BaseEntity.class.getName()),
                new Label(BaseLogicEntity.class.getName()),
                new Label(BasePureEntity.class.getName()),
                new Label("不需要"));
        box.getSelectionModel().selectFirst();
        box.setTooltip(new Tooltip(box.getItems().get(0).getText()));
        Label superClsLabel = new Label("实体类父类");
        superClsLabel.setTooltip(new Tooltip("实体类父类"));
        superClsLabel.setPrefWidth(80);
        superClsLabel.setAlignment(Pos.CENTER_RIGHT);
        superClsLabel.setTextOverrun(OverrunStyle.CENTER_WORD_ELLIPSIS);
        superClsBox.getChildren().addAll(superClsLabel, box);
        box.valueProperty().addListener((observableValue, oldLabel, newLabel) -> {
            newLabel.setTextFill(Paint.valueOf("black"));
            box.setTooltip(new Tooltip(newLabel.getText()));
            box.setFocusTraversable(true);
            superClsLabel.setTooltip(new Tooltip(newLabel.getText()));
        });

        vBox.getChildren().addAll(
                UIComponentUtil.wrapTextField(parentPkgTextField, "代码父包名"),
                superClsBox);
        Alert alert = UIComponentUtil.createCustomConfirm("代码配置", 300, 300, vBox);
        // 修改按钮描述
        alert.getDialogPane().getButtonTypes().setAll(
                new ButtonType("保存", ButtonBar.ButtonData.OK_DONE),
                new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE));

        alert.showAndWait().ifPresent(buttonType -> {
            if (ButtonType.OK.getButtonData().equals(buttonType.getButtonData())) {
                if (StringUtils.isEmpty(parentPkgTextField.getText())) {
                    UIComponentUtil.errorAlert("父包名不能为空");
                }
                CodeCache.parentEntity = box.getSelectionModel().getSelectedItem().getText();
                CodeCache.parentPackage = parentPkgTextField.getText().trim();
                UIComponentUtil.infoAlert("代码配置信息保存成功！");
                return;
            }
            UIComponentUtil.errorAlert("已取消操作！");
        });
    }
}